<script setup>

import {ref, onMounted, watch, computed} from 'vue';
import axios from "axios";
import {snackbar} from './store'

// 查询
const pageSize = ref(10);
const pageNo = ref(1);
const headers = [
    {title: '序号', key: 'num', sortable: false},
    {title: '名称', key: 'nickname', sortable: false},
    {title: '用户名', key: 'username', sortable: false},
    {title: '后台角色', key: 'roleId', sortable: false},
    {title: '巡检角色', key: 'checkRoleIds', sortable: false},
    {title: '后台部门', key: 'deptIds', sortable: false},
    {title: '巡检部门', key: 'checkDeptIds', sortable: false},
    {title: '职能科室', key: 'officeIds', sortable: false},
    {title: '职能科室角色', key: 'officeRole', sortable: false},
    {title: '手机号', key: 'phonenumber', sortable: false},
    {title: '状态', key: 'status', sortable: false},
    {title: '是否维修人员', key: 'userOrder', sortable: false},
    {title: '维修人员名称', key: 'usernameOrder', sortable: false},
    {title: '操作', key: 'actions', sortable: false}
];
const items = ref([]);
const loading = ref(true);
const totalItems = ref(0);

const search = ref('');
const name = ref(null);
const roleList = ref([]);
const roleListCheck = ref([]);
const deptList = ref([]);
const deptListCheck = ref([]);
const functionList = ref([]);
const updatePasswordType = ref(false);
watch(name, () => {
    search.value = name.value
})

function loadItems({page, itemsPerPage}) {
    loading.value = true;
    pageSize.value = itemsPerPage
    pageNo.value = page
    axios.post('/user/selectPage', {
        pageNo: page,
        pageSize: itemsPerPage,
        nickname: name.value === null ? null : name.value,
        delFlag: '0'
    }).then(({data}) => {
        items.value = data.data.records;
        totalItems.value = data.data.total;
        loading.value = false;
    })
}

onMounted(() => {
    loadItems({page: 1, itemsPerPage: pageSize.value});
    // 获取角色列表
    axios.post('/sys_role/role/selectPage', {
        pageNo: 1,
        pageSize: 100,
        delFlag: '0',
        remark: 1
    }).then(({data}) => {
        roleList.value = data.data.records;
    })
    axios.post('/sys_role/role/selectPage', {
        pageNo: 1,
        pageSize: 100,
        delFlag: '0',
        remark: 2
    }).then(({data}) => {
        roleListCheck.value = data.data.records;
    })
    axios.post('/sys_dept/sys-dept/selectPage', {
        pageNo: 1,
        pageSize: 1000
    }).then(({data}) => {
        deptList.value = data.data.records;
    })
    axios.post('/checkPlace/getAll', {}).then(({data}) => {
        deptListCheck.value = data.data;
    })
    axios.post('/checkFunctionOffice/getAll', {}).then(({data}) => {
        functionList.value = data.data;
    })
});

// 增改
const isShowDialog = ref(false)
const dialogEnum = {
    update: '编辑',
    create: '新增'
}
const dialogType = ref(null)
const isShowDeleteDialog = ref(false)
const editedItem = ref({
    nickname: null,
    password: "",
    phonenumber: "",
    roleId: "",
    username: "",
    status: "1"
});

function resetEditedItem() {
    editedItem.value = {
        nickname: null,
        password: "",
        phonenumber: "",
        roleId: "",
        username: "",
        status: "1"
    }
}

function updatePassword() {
    updatePasswordType.value = true;
    editedItem.value.password = ""
}

function clickNew() {
    dialogType.value = dialogEnum.create
    resetEditedItem()
    isShowDialog.value = true
}

function close() {
    isShowDialog.value = false
    resetEditedItem()
    dialogType.value = null
}

function clickEdit(item) {
    editedItem.value = Object.assign({}, item)
    if(editedItem.value.officeIds) {
        editedItem.value.officeIds = Number(editedItem.value.officeIds)
    }
    editedItem.value.deptIdss = editedItem.value.deptIds ? editedItem.value.deptIds.split(",").map(item => Number(item)) : []
    editedItem.value.checkDeptIdss = editedItem.value.checkDeptIds ? editedItem.value.checkDeptIds.split(",").map(item => Number(item)) : []
    delete editedItem.value.password
    editedItem.value.checkRoleIds = Number(editedItem.value.checkRoleIds)
    editedItem.value.roleIds = Number(editedItem.value.roleIds)
    updatePasswordType.value = false
    editedItem.value.status += ""
    editedItem.value.userOrder += ""
    isShowDialog.value = true
    dialogType.value = dialogEnum.update
}

function save() {
    if(!editedItem.value.nickname) {
        snackbar.info("请填写名称！")
        return
    }
    if(!editedItem.value.username) {
        snackbar.info("请填写用户名！")
        return
    }
    // if(!editedItem.value.roleIds) {
    //     snackbar.info("请选择后台角色！")
    //     return
    // }
    // if(!editedItem.value.checkRoleIds) {
    //     snackbar.info("请选择巡检角色！")
    //     return
    // }
    // if(!editedItem.value.deptIdss.length) {
    //     snackbar.info("请选择后台部门！")
    //     return
    // }
    // if(!editedItem.value.checkDeptIdss.length) {
    //     snackbar.info("请选择巡检部门！")
    //     return
    // }
    // if(!editedItem.value.officeIds) {
    //     snackbar.info("请选择职能科室！")
    //     return
    // }
    // if(!editedItem.value.officeRole) {
    //     snackbar.info("请选择职能科室角色！")
    //     return
    // }
    editedItem.value.checkDeptIds = editedItem.value.checkDeptIdss.join(",")
    editedItem.value.checkRoleIds += ''
    if(editedItem.value.officeIds) {
        editedItem.value.officeIds += ''
    }
    editedItem.value.roleIds += ''
    editedItem.value.deptIds = editedItem.value.deptIdss.join(",");
    if (dialogType.value === dialogEnum.update) {
        axios({
            method: 'POST',
            url: '/user/updateUser',
            data: editedItem.value
        }).then(() => {
            snackbar.info('编辑成功')
            close()
            loadItems({page: pageNo.value, itemsPerPage: pageSize.value})
        })
    } else if (dialogType.value === dialogEnum.create) {
        axios({
            method: 'POST',
            url: '/user/saveUser',
            data: editedItem.value
        }).then(() => {
            snackbar.info('创建成功')
            close()
            loadItems({page: pageNo.value, itemsPerPage: pageSize.value})
        })
    }
}

// 删
const beDeleteItem = ref({})

function clickDelete(item) {
    isShowDeleteDialog.value = true
    beDeleteItem.value = item
}

function clickDeleteConfirm() {
    axios.post('/user/delUser/?userId=' + beDeleteItem.value.id).then(() => {
        snackbar.info("删除成功")
        loadItems({page: 1, itemsPerPage: pageSize.value})
        clickCloseDelete()
    })
}

function clickCloseDelete() {
    isShowDeleteDialog.value = false
    beDeleteItem.value = null
}

</script>

<template>
    <v-toolbar density="compact">
        <v-toolbar-title>用户管理</v-toolbar-title>
        <v-text-field v-model="name" :clearable="true" hide-details placeholder="查询名称"></v-text-field>
        <v-dialog v-model="isShowDialog" max-width="500px">
            <template v-slot:activator="{ props }">
                <v-btn icon="mdi-plus" v-on:click="clickNew" v-bind="props"></v-btn>
            </template>
            <v-card>
                <v-card-title>{{ dialogType }}</v-card-title>
                <v-card-text>
                    <v-text-field v-model="editedItem.nickname" label="名称" required></v-text-field>
                    <v-text-field v-model="editedItem.username" label="用户名" required></v-text-field>
                    <v-text-field v-if="dialogType == dialogEnum.create || updatePasswordType" v-model="editedItem.password" label="密码" required></v-text-field>
                    <v-select
                    v-model="editedItem.roleIds"
                    :items=roleList
                    item-title="name"
                    item-value="id"
                    label="后台角色"
                    required></v-select>
                    <v-select
                    v-model="editedItem.checkRoleIds"
                    :items=roleListCheck
                    item-title="name"
                    item-value="id"
                    label="巡检角色"></v-select>
                    <v-autocomplete
                    v-model="editedItem.deptIdss"
                    :items=deptList
                    item-title="deptName"
                    item-value="deptId"
                    label="后台部门"
                    multiple></v-autocomplete>
                    <v-autocomplete
                    v-model="editedItem.checkDeptIdss"
                    :items=deptListCheck
                    item-title="placeName"
                    item-value="id"
                    label="巡检部门"
                    multiple></v-autocomplete>
                    <v-select
                    v-model="editedItem.officeIds"
                    :items=functionList
                    item-title="officeName"
                    item-value="id"
                    label="职能科室"
                    ></v-select>
                    <v-select
                    v-model="editedItem.officeRole"
                    :items="[{value: '0', title: '科员'},{value: '1', title: '科长'}]"
                    label="职能科室角色"
                    ></v-select>
                    <v-text-field v-model="editedItem.phonenumber" label="手机号"></v-text-field>
                    <v-select
                    v-model="editedItem.status"
                    :items="[{value:'1',title:'正常'},
                    {value:'2',title:'停用'}]"
                    label="用户状态"></v-select>
                    <v-select
                    v-model="editedItem.userOrder"
                    :items="[{value:'1',title:'是'},
                    {value:'2',title:'否'}]"
                    label="是否维修人员"></v-select>
                    <v-text-field v-model="editedItem.usernameOrder" label="维修人员名称" required></v-text-field>
                </v-card-text>
                <v-card-actions>
                    <v-btn color="primary" variant="text" @click="close">关闭</v-btn>
                    <v-btn color="primary" variant="text" @click="save">确定</v-btn>
                    <v-btn color="primary" variant="text" @click="updatePassword">修改密码</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
        <v-dialog v-model="isShowDeleteDialog" max-width="500px">
            <v-card>
                <v-card-title class="text-h5">确定删除?</v-card-title>
                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn color="blue-darken-1" variant="text" @click="clickCloseDelete">取消</v-btn>
                    <v-btn color="blue-darken-1" variant="text" @click="clickDeleteConfirm">确定</v-btn>
                    <v-spacer></v-spacer>
                </v-card-actions>
            </v-card>
        </v-dialog>
    </v-toolbar>
  <!--  分页文本待更换   items-per-page-text="每页数量"-->
    <v-data-table-server :search="search" :items-per-page="pageSize" :headers="headers" :items-length="totalItems"
    :items="items"
    :loading="loading"
    class="elevation-1"
    items-per-page-text="每页数量"
    @update:options="loadItems">
        <template v-slot:item.num="{ index }">
            <span>{{ index + 1 }}</span>
        </template>
        <template v-slot:item.roleId="{ item }">
            <span v-for="role in roleList" v-show="role.id == item.raw.roleId">{{ role.name }}</span>
        </template>
        <template v-slot:item.checkRoleIds="{ item }">
            <span v-for="role in roleListCheck" v-show="role.id == item.raw.checkRoleIds">{{ role.name }}</span>
        </template>
        <template v-slot:item.deptIds="{ item }">
            <span v-if="item.raw.deptIds" v-for="k in item.raw.deptIds.split(',')">
                <span v-for="role in deptList" v-show="role.deptId == k">{{ role.deptName }}&nbsp;&nbsp;&nbsp;</span>
            </span>
        </template>
        <template v-slot:item.checkDeptIds="{ item }">
            <span v-if="item.raw.checkDeptIds" v-for="k in item.raw.checkDeptIds.split(',')">
                <span v-for="role in deptListCheck" v-show="role.id == k">{{ role.placeName }}&nbsp;&nbsp;&nbsp;</span>
            </span>
        </template>
        <template v-slot:item.officeIds="{ item }">
            <span v-for="role in functionList" v-show="role.id == item.raw.officeIds">{{ role.officeName }}</span>
        </template>
        <template v-slot:item.status="{ item }">
            <span v-if="item.raw.status == 1">正常</span>
            <span v-if="item.raw.status == 2">停用</span>
        </template>
        <template v-slot:item.userOrder="{ item }">
            <span v-if="item.raw.userOrder == 1">是</span>
        </template>
        <template v-slot:item.officeRole="{ item }">
            <span v-if="item.raw.officeRole == 1">科长</span>
            <span v-if="item.raw.officeRole == 0">科员</span>
        </template>
        <template v-slot:item.actions="{ item }">
            <v-btn icon="mdi-pencil" variant="text" @click="clickEdit(item.raw)"></v-btn>
            <v-btn icon="mdi-delete" variant="text" @click="clickDelete(item.raw)"></v-btn>
        </template>
    </v-data-table-server>
</template>

<style scoped lang="less">

</style>
